﻿using System;
using System.Collections.Generic;
using System.Linq;
using Skynet.CommonLibrary.ExceptionEx.Config;
using Skynet.CommonLibrary.ExceptionEx.Inteface;
using Skynet.CommonLibrary.ExceptionEx.LogHandler;

namespace Skynet.CommonLibrary.ExceptionEx
{
    internal class ExceptionManager
    {
        readonly List<ExceptionConfigEntity> _exList;
        readonly IExceptionDataSource _dataSourceOperate;
       internal ExceptionManager()
       {
           LogHandler = new DefaultLogHandler();
          _exList = ReadConfig.Read(out _dataSourceOperate);
       }
       internal ILogHandler LogHandler { get; set; }

       internal void ProcessException(Exception ex, string layerName, string friendlyInfo)
       {
           Process(layerName, () => LogHandler.SaveLogInfo(_dataSourceOperate, ex, friendlyInfo, layerName));
       }
       internal void ProcessException(Exception ex, int exID)
       {
           Process(string.Empty, () => LogHandler.FindLogInfo(_dataSourceOperate, ex, exID));
       }

        //处理异常
       private void Process(string layerName, Func<ExceptionEntity> loginfoAction)
       {
           try
           {
               ExceptionConfigEntity config = _exList.FirstOrDefault(o => o.Name == layerName) ??
                                              _exList.FirstOrDefault(o => o.Name == "Default");

               if (config != null)
               {
                   //错误编号
                   ExceptionEntity exEntity = loginfoAction();

                   //是否需要输出错误信息
                   if (config.MsgMode != ExShowMsgType.None)
                   {
                       config.OutMessage.ShowMessage(string.Format("错误ID：{0}{1}内容：{2}",
                           exEntity.ExId,
                           Environment.NewLine,
                           exEntity.FriendlyInfo));
                   }

                   //是否抛出异常
                   if (config.ReturnMode == ExReturnMode.Exception)
                   {
                       throw new Exception(string.Format("错误ID：{0}{1}内容：{2}", exEntity.ExId, Environment.NewLine, exEntity.FriendlyInfo));
                   }
               }
           }
           catch (Exception ex)
           {
               log4net.LogManager.GetLogger("ErrorLog").Error(
                string.Format("{0}{1}.错误路径:{2}{1}.错误信息:{3}{1}",
                 layerName,
                Environment.NewLine,
                "ExceptionManager--process",
                ex.Message));
           }
       }
    }
}
